package com.lc.activiti.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import java.beans.FeatureDescriptor;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Title: WebSocketEncoder
 * @Description:
 * @author: 骆超
 * @date: 2021/7/7 14:30
 */
public class WebSocketEncoder implements Encoder.Text<Result> {

    @Override
    public String encode(Result object) throws EncodeException {
       if (object.getData() instanceof String){
           return JSONUtil.toJsonStr(object);
       }else{
           BeanWrapper bw = new BeanWrapperImpl(object.getData());
           PropertyDescriptor[] pd = bw.getPropertyDescriptors();
           JSONObject jsonObject = new JSONObject();
           Arrays.stream(pd).filter(f-> ObjectUtil.isNotEmpty(bw.getPropertyValue(f.getName()))).forEach(v->{
               jsonObject.putIfAbsent(v.getName(),bw.getPropertyValue(v.getName())+"");
           });
           JSONObject parseObj = JSONUtil.parseObj(object.getData());
           parseObj.putAll(jsonObject);
           //将java对象转换为json字符串
           return JSONUtil.toJsonStr(object.setData(parseObj));
       }
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
}
